# -*- coding: utf-8 -*-

"""
@author: 李强
@contact: QQ:1206709430
@Created on: 2021/7/30
@Remark: 租户信息管理
"""
from django.db import connection
from django_tenants.utils import tenant_context

from dvadmin.system.models import Users
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from plugins.dvadmin_tenant_backend.management.commands.tenant_init import Command
from plugins.dvadmin_tenant_backend.models import Client


class ClientSerializer(CustomModelSerializer):
    """
    租户信息-序列化器
    """

    class Meta:
        model = Client
        fields = "__all__"
        read_only_fields = ["id"]

    def create(self, validated_data):
        instance = super().create(validated_data)
        # 初始化信息
        with tenant_context(instance):
            res = Command()
            res.run()
        # 创建默认用户
        user, _ = Users.objects.get_or_create(username=instance.schema_name, name=f'[ak/sk]{instance.name}',
                                              defaults={'dept_id': 'd2c03bd9-dad0-4262-88ca-c3681d224fc3'})
        user.role.set(['35b58d98-b506-4f93-be79-ed1e109da071'])
        return instance

    def update(self, instance, validated_data):
        instance = super().update(instance, validated_data)
        # 更新默认用户
        user, _ = Users.objects.get_or_create(username=instance.schema_name,
                                              defaults={'name': f'[ak/sk]{instance.name}',
                                                        'dept_id': 'd2c03bd9-dad0-4262-88ca-c3681d224fc3'})
        user.role.set(['35b58d98-b506-4f93-be79-ed1e109da071'])
        return instance


class ClientCreateUpdateSerializer(CustomModelSerializer):
    """
    租户信息管理 创建/更新时的列化器
    """

    class Meta:
        model = Client
        fields = '__all__'


class ClientViewSet(CustomModelViewSet):
    """
    租户信息管理接口:
    """
    queryset = Client.objects.all()
    serializer_class = ClientSerializer
    filter_fields = ['name', 'schema_name']

    def get_queryset(self):
        queryset = super().get_queryset()
        if connection.tenant.schema_name != 'public':
            queryset = queryset.filter(schema_name=connection.tenant.schema_name)
        return queryset
